package com.example.demo.service.impl;

import com.example.demo.Util.Result;
import com.example.demo.Util.ResultUtil;
import com.example.demo.mapper.TeacherMap;
import com.example.demo.mapper.UserMap;
import com.example.demo.po.Teacher;
import com.example.demo.po.User;
import com.example.demo.po.dto.TeacherAddParam;
import com.example.demo.po.dto.TeacherParam;
import com.example.demo.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    TeacherMap teacherMap;

    @Autowired
    UserMap userMap;

    @Override
    public List<Teacher> SearchTeacher(String name, int id) {

        if(!StringUtils.isEmpty(name)&& id != -1){

           return     teacherMap.GetTeacherByNameAndId("%"+name+"%",id);
        }else if(!StringUtils.isEmpty(name)){

            return teacherMap.GetTeacherByName("%"+name+"%");
        }else {

            return teacherMap.GetTeacherById(id);
        }


    }

    @Override
    public Result SaveTeacher(TeacherAddParam teacherAddParam) {

        if(StringUtils.isEmpty(teacherAddParam.getName())||StringUtils.isEmpty(teacherAddParam.getPassword())||StringUtils.isEmpty(teacherAddParam.getUsername()))
        {
            return ResultUtil.fail("名称、用户名、密码必填");
        }
        if(teacherAddParam.getCollegeid() == 0){
            return ResultUtil.fail("学院必填");
        }
        List<User> l =  userMap.getUserByLogin(teacherAddParam.getUsername());
        if( l !=null && l.size()>0 ){
            return  ResultUtil.fail("用户名重名");
        }

       //添加user
        User user = new User();
        user.setNickname(teacherAddParam.getName());
        user.setUsername(teacherAddParam.getUsername());
        user.setPassword(teacherAddParam.getPassword());
        user.setRole(teacherAddParam.getRole());
        userMap.SaveUser(user);

        //添加teacher
        teacherAddParam.setUserid(user.getId());
        teacherMap.SaveTeacherByAdd(teacherAddParam);




        return ResultUtil.success(teacherAddParam);
    }

    @Override
    public Result UpdateTeacher(TeacherParam TeacherParam) {
        if(StringUtils.isEmpty(TeacherParam.getName()))
        {
            return ResultUtil.fail("用户名必填");
        }

        if(TeacherParam == null){
            return ResultUtil.fail("更新失败");
        }
        if(TeacherParam.getCollegeid() == 0){
            return ResultUtil.fail("学院必填");
        }

        //更新teacher信息
        teacherMap.UpdateTeacher(TeacherParam);
        //更新user冗余字段
        userMap.UpdateUserNickName(TeacherParam.getUserid(),TeacherParam.getName());

        return ResultUtil.success(TeacherParam);
    }
}
